package core.form.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;

import javax.inject.Inject;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

import util.StringUtil;
import util.uuid.Sequence;
import util.uuid.SequenceException;
import cn.org.rapid_framework.page.Page;
import core.base.action.BasePageRequest;
import core.form.dao.FormDao;
import core.form.model.Form;
import core.form.service.FormService;

@Service
public class FormServiceImpl implements FormService {
	@Inject
	public FormDao formDao;

	public void saveForm(Form vo) {
		try {
			if (StringUtil.isBlank(vo.getId())) {
				vo.setId(Sequence.getSequence());
			}
			formDao.saveForm(vo);
		} catch (SequenceException e) {
			throw new RuntimeException(e);
		}
	}

	public void updateForm(Form vo) {
		try {
			Form po = formDao.findForm(vo.getId());
			if (po != null) {
				BeanUtils.copyProperties(po, vo);
				formDao.updateForm(po);
			} else {
				if (StringUtil.isBlank(vo.getId())) {
					vo.setId(Sequence.getSequence());
				}
				formDao.saveForm(vo);
			}

		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		} catch (SequenceException e) {
			throw new RuntimeException(e);
		}
	}

	public void saveOrUpdateForm(Form vo) {
		if (vo != null) {
			if (StringUtil.isBlank(vo.getId())) {
				vo.setCreated(new Date());
				saveForm(vo);
			} else {
				updateForm(vo);
			}
		}
	}

	public void deleteForm(String id) {
		formDao.deleteForm(id);
	}

	public void deleteForms(String[] ids) {
		formDao.deleteForms(ids);
	}

	public Form findForm(String id) {
		return formDao.findForm(id);
	}
	
	public Page<Form> listForms(BasePageRequest pageRequest) {
		return formDao.queryForms(pageRequest);
	}

}
